package com.examination.exam.service.impl;

import com.examination.auth.utils.JacksonUtil;
import com.examination.domain.exam.entity.Question;
import com.examination.exam.mapper.QuestionMapper;
import com.examination.exam.service.QuestionService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class QuestionServiceImpl implements QuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    @Override
    public Question getQuestionById(Object id) {
        return questionMapper.queryById(id);
    }

    @Override
    public List<Question> getQuestionByQuery(Bson query) {
        return questionMapper.query(query);
    }

    @Override
    public long updateQuestion(Bson filter, Bson bson) {
        return questionMapper.updateMany(filter, bson).getModifiedCount();
    }

    @Override
    public boolean removeById(Long id) {
        long l = questionMapper.deleteById(id);
        if (l != 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void addQuestion(Question question) {
        try {
            Map<String, Object> stringObjectMap = JacksonUtil.jsonToMap(JacksonUtil.toJsonString(question));
            stringObjectMap.remove("id");
            Document document = Document.parse(JacksonUtil.toJsonString(stringObjectMap));
            questionMapper.insertOne(document);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

}
